package cn.car91.activity;

import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.ViewFlipper;
import cn.car91.R;
import cn.car91.activity.MapActivity.MapType;
import cn.car91.adapter.SpreadListAdapter;
import cn.car91.bean.RepairShop;
import cn.car91.http.HttpHandler;
import cn.car91.utils.Car91JsonUtil;
import cn.car91.utils.ImageManager;
import cn.car91.utils.RegexUtil;
import cn.car91.view.HerilyAlertDialog.Builder;
import cn.car91.view.MyListView;
import cn.car91.view.PageControlView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.thinkland.sdk.android.DataCallBack;
import com.thinkland.sdk.android.JuheData;
import com.thinkland.sdk.android.Parameters;

public class MainActivity extends BaseFragment {
    SharedPreferences sharedPreferences;
    SharedPreferences otherPreferences;

    LocationClient mLocationClient;
    String cityname;
//天气
    @ViewInject(R.id.weather)
    View weatherView;
    TextView wCityView;
    TextView wDateView;
    TextView wInfoView;
    ImageView wTypeView;
    TextView wWindView;
    TextView wLifeGradeView;
    TextView wLifeInfoView;
    TextView wMoonView;
    TextView wTemperatureView;
//油价
    @ViewInject(R.id.oil_city)
    TextView oilCityView;
    @ViewInject(R.id.oil_0)
    TextView oil0View;
    @ViewInject(R.id.oil_90)
    TextView oil90View;
    @ViewInject(R.id.oil_93)
    TextView oil93View;
    @ViewInject(R.id.oil_97)
    TextView oil97View;

    @ViewInject(R.id.spread)
    MyListView spreadListView;

    ViewFlipper viewFlipper;
    PageControlView pageControlView;

    List<View> uiViews;
    
    SpreadListAdapter spreadAdapter;

    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.activity_main, container, false);
		
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		sharedPreferences = getCar91Application().getPlacePreferences();
    otherPreferences = getCar91Application().getOtherPreferences();

        new Handler().postDelayed(new Runnable() {
            public void run() {
                if (!getCar91Application().isLocating()) {
                    new Builder(getActivity()).setMessage("网络环境较差，定位可能需花点时间").create().show();
                }
            }
        }, 8 * 1000);

        mLocationClient = getCar91Application().getmLocationClient();

        spreadAdapter = new SpreadListAdapter(getActivity());
        spreadListView.setAdapter(spreadAdapter);
        
        initView();
        
        btnBindClickEvent();
	}

    private void initView() {
        wCityView = (TextView) weatherView.findViewById(R.id.weather_city);
        wDateView = (TextView) weatherView.findViewById(R.id.weather_date);
        wInfoView = (TextView) weatherView.findViewById(R.id.weather_info);
        wTypeView = (ImageView) weatherView.findViewById(R.id.weather_type);
        wWindView = (TextView) weatherView.findViewById(R.id.weather_wind);
        wLifeGradeView = (TextView) weatherView.findViewById(R.id.weather_life_grade);
        wLifeInfoView = (TextView) weatherView.findViewById(R.id.weather_life_info);
        wMoonView = (TextView) weatherView.findViewById(R.id.weather_moon);
        wTemperatureView = (TextView) weatherView.findViewById(R.id.weather_temperature);

        initUIData();
        initSpread();
    	/*Intent intent = new Intent(Intent.ACTION_MAIN,Uri.parse("intent:#Intent;action=android.intent.action.MAIN;category=android.intent.category.LAUNCHER;launchFlags=0x10000000;component=com.sina.weibo/.MainTabActivity;end"));
    	startActivity(intent);*/
    }

    @Override
	public void onResume() {
        super.onResume();

        SharedPreferences.Editor editor = otherPreferences.edit();
        editor.remove("item");
        editor.remove("searchKey");
        editor.commit();

        mLocationClient.registerLocationListener(locationListener);
        if (!mLocationClient.isStarted())
            mLocationClient.start();

        if (mLocationClient.isStarted())
            mLocationClient.requestOfflineLocation();
    }

    private void btnBindClickEvent() {
        TableRow trRow_1 = (TableRow) getView().findViewById(R.id.tableRow_nav_1);
        if (trRow_1 != null) {
            for (int i = 0; i < trRow_1.getChildCount(); i++) {
                Button btn = (Button) trRow_1.getChildAt(i);
                btn.setOnClickListener(onClickListener);
            }
        }
    }

    BDLocationListener locationListener = new BDLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation arg0) {
            // TODO Auto-generated method stub
            cityname = arg0.getCity();
            try {
                if (RegexUtil.isNull(cityname)) {
                    if (arg0 != null) {
                        cityname = arg0.getCity();
                    }
                }
            } catch (Exception e) {
            }
            getCar91Application().setLocating(true);
            mLocationClient.stop();

            RequestParams params = new RequestParams("utf-8");
            params.addBodyParameter("method", "index");
            params.addBodyParameter("city", cityname);

            HttpHandler.httpHandler.getWeather(cityname, callBackWeather);
            HttpHandler.httpHandler.getOil(cityname, callBackOil);
        }
    };
    private void initUIData() {
        LocationClientOption option = mLocationClient.getLocOption();
        option.setAddrType("all");
        mLocationClient.setLocOption(option);

        initWeatherData(otherPreferences.getString("todayweather", ""));
    }

    //天气控件 START
    RequestCallBack callBackWeather = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
            initWeatherSecond();
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            String result = arg0.result.toString();
            if (RegexUtil.isNull(result)) {
                initWeatherSecond();
            } else {
                initWeatherData(result);
            }
        }
    };

    private void initWeatherSecond() {
        try {
            if (RegexUtil.isNotNull(cityname)) {
            	HttpHandler.httpHandler.getAPIWeather(cityname, new DataCallBack() {
                    @Override
                    public void resultLoaded(int err, String arg1, String result) {
                        if (err == 0) {
                            if (RegexUtil.isNotNull(result)) {
                            	try {
                            		JSONObject jsonObject = JSONObject.parseObject(result);
                                    if (jsonObject.getString("error_code").equals("0")) {
                                        String resultJson = jsonObject.getString("result");
                                        HttpHandler.httpHandler.saveAPIWeather(cityname, resultJson, null);
                                        initWeatherData(resultJson);
                                    }
								} catch (Exception e) {}
                            }
                        }
                    }
                });
            }
        } catch (Exception e) {
        }
    }

    private void initWeatherData(String resultJson) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(resultJson);
            JSONObject dataObject = jsonObject.getJSONObject("data");
            JSONObject realtimeObject = dataObject.getJSONObject("realtime");
            String city = realtimeObject.getString("city_name");
            wCityView.setText(city);
            String date = realtimeObject.getString("date");
            wDateView.setText(date);
            String moon = realtimeObject.getString("moon");
            wMoonView.setText(moon);
            JSONObject weatherObject = realtimeObject.getJSONObject("weather");
            String temperature = weatherObject.getString("temperature");
            String img = weatherObject.getString("img");
            if (img.length() < 2) {
                img = "0" + img;
            }
            wTemperatureView.setText(temperature + "°c");
            String info = weatherObject.getString("info");
            wInfoView.setText(info);
            JSONObject windObject = realtimeObject.getJSONObject("wind");
            String wind = windObject.getString("direct") + windObject.getString("power");
            wWindView.setText(wind);
            JSONObject lifeObject = dataObject.getJSONObject("life");
            JSONObject infoObject = lifeObject.getJSONObject("info");
            JSONArray xicheArray = infoObject.getJSONArray("xiche");
            String xicheGrade = xicheArray.getString(0);
            String xicheSuggest = xicheArray.getString(1);
            wLifeGradeView.setText("洗车指数: " + xicheGrade);
            wLifeInfoView.setText(xicheSuggest);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            if (calendar.get(Calendar.HOUR_OF_DAY) < 19 && calendar.get(Calendar.HOUR_OF_DAY) >= 7)
                img = "d" + img;
            else
                img = "n" + img;
            ImageManager imageManager = new ImageManager(getActivity(), "sdcard/car91/temp/weather");
            imageManager.displayImage(null, weatherView, getResources().getDrawable(R.drawable.weather_bg_default));
            imageManager.displayImage("http://i.tq121.com.cn/i/wap/80bai/" + img + ".png", wTypeView, getResources().getDrawable(R.drawable.weather_default));
            Editor editor = otherPreferences.edit();
            editor.putString("todayweather", resultJson);
            editor.commit();
        } catch (Exception e) {
            LogUtils.e(e.toString());
        }
    }
    //天气控件 END

    //实时油价 START
    RequestCallBack callBackOil = new RequestCallBack() {
        @Override
        public void onFailure(HttpException arg0, String arg1) {
            initWeatherSecond();
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            String result = arg0.result.toString();
            if (RegexUtil.isNull(result)) {
                initOilSecond();
            } else {
                initOilData(result);
            }
        }
    };

    private void initOilSecond() {
        try {
            if (RegexUtil.isNotNull(cityname)) {
                Parameters params = new Parameters();
                params.add("city", URLEncoder.encode(cityname.trim(), "UTF-8"));
                JuheData.executeWithAPI(getCar91Application().apiOilId, "http://apis.juhe.cn/oil/region", JuheData.GET, params, new DataCallBack() {
                    @Override
                    public void resultLoaded(int err, String arg1, String result) {
                        if (err == 0) {
                            try {
                                JSONObject jsonObject = JSONObject.parseObject(result);
                                if (jsonObject.getString("resultcode").equals("200")) {
                                    String resultJson = jsonObject.getString("result");
                                    HttpHandler.httpHandler.saveAPIOil(cityname, resultJson, null);
                                    initOilData(resultJson);
                                }
                            } catch (Exception e) {}
                        }
                    }
                });
            }
        } catch (Exception e) {
            LogUtils.e(e.toString());
        }
    }

    private void initOilData(String resultJson) {
        try {
            Editor editor = otherPreferences.edit();
            editor.putString("oilJson", resultJson);
            editor.commit();
            JSONObject jsonObject = JSONObject.parseObject(resultJson);
            JSONArray dataObject = jsonObject.getJSONArray("data");
            oilCityView.setText(cityname + "今日油价");
            if (dataObject.size() > 0) {
                JSONObject oilObject = dataObject.getJSONObject(0);
                JSONObject priceObject = oilObject.getJSONObject("price");
                Iterator<Entry<String, Object>> allprice = priceObject.entrySet().iterator();
                while (allprice.hasNext()) {
                    Entry<String, Object> tmp = allprice.next();
                    String tprice = (String) tmp.getValue();
                    if (tmp.getKey().equals("E0"))
                        oil0View.setText(tprice + "元/升");
                    else if (tmp.getKey().equals("E90") || tmp.getKey().equals("E89"))
                        oil90View.setText(tprice + "元/升");
                    else if (tmp.getKey().equals("E93") || tmp.getKey().equals("E92"))
                        oil93View.setText(tprice + "元/升");
                    else if (tmp.getKey().equals("E97") || tmp.getKey().equals("E95"))
                        oil97View.setText(tprice + "元/升");
                }
            }
        } catch (Exception e) {
            LogUtils.e(e.toString());
        }
    }

    @OnClick(R.id.oil)
    public void onOilClick(View view) {
        Intent intent = new Intent(getActivity(), OilActivity.class);
        intent.putExtra("cname", cityname);
        startActivity(intent);
    	/*Uri mUri = Uri.parse("geo:39.940409,116.355257?q=西直门");
    	Intent mIntent = new Intent(Intent.ACTION_VIEW,mUri);
    	startActivity(mIntent);*/
    }
    //实时油价 END

    //推广
    private void initSpread() {
    	HttpHandler.httpHandler.getSpread(1, callBackSpread);
    	spreadListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				String rid = spreadAdapter.getRepairShopId(arg2);

		        Intent intent = new Intent();
		        intent.putExtra("rid", rid);
		        intent.setClass(getActivity(), RepairShopDetailActivity.class);
		        startActivity(intent);
			}
		});
    }

    RequestCallBack callBackSpread = new RequestCallBack() {

        @Override
        public void onFailure(HttpException arg0, String arg1) {
        }

        @Override
        public void onSuccess(ResponseInfo arg0) {
            List<RepairShop> repairShops = Car91JsonUtil.getDTOList(arg0.result.toString(), RepairShop.class);
            spreadAdapter.setmList(repairShops);
            spreadAdapter.notifyDataSetChanged();
        }
    };
    //推广END

    OnClickListener onClickListener = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            int id = arg0.getId();
            switch (id) {
                case R.id.view_nav_item_illegal:
                    Intent iintent = new Intent(getActivity(), IllegalMainActivity.class);
                    startActivity(iintent);
                    break;
                case R.id.view_nav_item_traffic:
                    if (getCar91Application().isLocating()) {
                        Intent mintent = new Intent(getActivity(), MapActivity.class);
                        mintent.putExtra("mapType", MapType.MAP_TYPE_AOUND_TRAFFIC);
                        mintent.putExtra("lon", mLocationClient.getLastKnownLocation().getLongitude());//2G和3G异常
                        mintent.putExtra("lat", mLocationClient.getLastKnownLocation().getLatitude());
                        mintent.putExtra("zoom", 16);
                        if (mLocationClient.isStarted())
                            mLocationClient.stop();
                        mLocationClient.unRegisterLocationListener(locationListener);
                        startActivity(mintent);
                    } else {
                        new Builder(getActivity()).setMessage("正在定位中...").create().show();
                    }
                    break;
                case R.id.view_nav_item_aidphone:
                    Intent aintent = new Intent(getActivity(), AidActivity.class);
                    startActivity(aintent);
                    break;
                case R.id.view_nav_item_aroundservice:
                    Intent rintent = new Intent(getActivity(), RoundActivity.class);
                    startActivity(rintent);
                    break;

                default:
                    break;
            }
        }
    };

    @Override
	public void onDestroy() {
        // TODO Auto-generated method stub
        try {
            if (mLocationClient.isStarted())
                mLocationClient.stop();
            mLocationClient.unRegisterLocationListener(locationListener);
        } catch (Exception e) {
        }
        super.onDestroy();
    }
}
